<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<video autoplay controls id="local" style="width: 200px;"></video>
<video autoplay controls id="remote"></video>
<script src="./socket.io.min.js"></script>
<script src="./socket.js"></script>
<script>
  const $remote = document.querySelector('#remote');
  const cacheCandidate = []
  let pc


  /**
   * 收到对端消息
   */
  const socket = useSocket(userB, () => {
    socket.on('message:ice', ({ data }) => {
      /**
       * 收到对端 ICE
       */
      console.log('收到： ice')
      const ice = new RTCIceCandidate(data)
      if (!pc) {
        cacheCandidate.push(ice)
      } else {
        pc.addIceCandidate(ice)
      }
    })

    socket.on('message:offer', ({ data }) => {
      // 打开摄像头
      startWebRTC().then (() => {
        /**
         * 收到对端 OFFER，保存对端 OFFER
         */
        console.log('收到： offer', data)
        pc.setRemoteDescription(new RTCSessionDescription(data)).then(_ => {
          while (cacheCandidate.length > 1) {
            const ice = cacheCandidate.shift()
            if (ice) {
              pc.addIceCandidate(ice)
            }
          }
          // 创建应答
          pc.createAnswer().then(function(description) {
            console.log('创建： answer', description)
            // 保存本地描述
            return pc.setLocalDescription(description);
          }).then(function() {
            const { sdp } = pc.localDescription
            console.log('发送： answer')

            socket.emit('message:answer', { member: userA, data: { type: "answer", sdp: sdp }})
          })
        })
      })
    })
  })

  /**
   * 获取到本机 ICE，发送给对端
   *
   * @param event
   */
  function onIceCandidate (event) {
    if (event.candidate) {
      const candidate = event.candidate.toJSON()
      console.log('发送：ice', candidate)
      socket.emit('message:ice', { member: userA, data: candidate })
    }
  }

  /**
   * 创建 WebRTC
   */

  /**
   * 创建 WebRTC
   */
  function startWebRTC() {
    const configuration = {
      iceServers: [
        {'urls': 'stun:stun.stunprotocol.org:3478'},
        {'urls': 'stun:stun.l.google.com:19302'},
      ]
    };
    pc = new RTCPeerConnection(configuration)

    pc.addEventListener('icecandidate', onIceCandidate)
    /**
     * 获取到对端的 流
     *
     * @param event
     */
    pc.ontrack = (event) => {
      console.log('ontrack： 收到对端的流，打开对端视频 ')
      if ($remote.srcObject) return;
      $remote.srcObject = event.streams[0];
    };
    return Promise.resolve()
  }

</script>
</body>
</html>
